package com.app.Cutofftime;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.res.ResourcesCompat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.app.Cutofftime.Database.DatabaseHelper;
import com.google.android.material.snackbar.Snackbar;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ViewingActivity extends AppCompatActivity {

    private DatabaseHelper helper;
    private TableLayout tableLayout;
    private TableRow.LayoutParams params;
    List<AssItem> data = new ArrayList<AssItem>();
    private Spinner spinner;
    private List<String> data_list;
    private ArrayAdapter<String> arr_adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewing);

        //筛选下拉框
        spinner = (Spinner) findViewById(R.id.spinner);
        data_list = new ArrayList<String>();
        data_list.add("ALL");
        data_list.add("Next Week");
        data_list.add("Next Month");
        data_list.add("In Processing");
        data_list.add("Past Month");
        data_list.add("Overdue");
        arr_adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arr_adapter);


        Toolbar toolbar = findViewById(R.id.bar7);
        toolbar.setTitle("All course work");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        helper = new DatabaseHelper(getApplicationContext());
//        tableLayout = findViewById(R.id.cut2);

        Cursor cursor = helper.viewTimelimit();

        int row_id = 1;

        if (cursor.getCount() == 0) {
//            Snackbar.make(view, "add", Snackbar.LENGTH_SHORT).show();
        } else {

            while (cursor.moveToNext()) {
                AssItem i = new AssItem(
                        cursor.getString(1),
                        cursor.getString(2),
                        cursor.getString(5),
                        cursor.getString(6),
                        cursor.getInt(0),
                        cursor.getString(3),
                        cursor.getInt(7),
                        cursor.getString(4)
                        );
                data.add(i);
//                addRow(cursor, row_id);
                row_id++;
            }
            data = sortAss(data);
            AssAdapter adapter=new AssAdapter(ViewingActivity.this,R.layout.list_item,data);
            ListView listview = (ListView) findViewById(R.id.list_view);
            listview.setAdapter(adapter);
        }

        //添加监听
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            //当选中某一个数据项时触发该方法
            /*
             * parent接收的是被选择的数据项所属的 Spinner对象，
             * position接收的是被选择的数据项在适配器中的位置
             * id被选择的数据项的行号
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                List<AssItem> newList = new ArrayList<AssItem>() ;
                //1-next week;2-next month;3-ALl in processing;4-pass week;5-all pass
                if (position==0) newList = data;
                if (position==1) newList = getTimeLine(rlist1,0,168);
                if (position==2) newList = getTimeLine(rlist1,0,720);
                if (position==3) newList = rlist1;
                if (position==4) newList = getTimeLine(rlist2,-168,0);
                if (position==5) newList = rlist2;
                AssAdapter adapter=new AssAdapter(ViewingActivity.this,R.layout.list_item,newList);
                ListView listview = (ListView) findViewById(R.id.list_view);
                listview.setAdapter(adapter);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });


    }
    List<AssItem> rlist1 = new ArrayList<AssItem>() ;//all in processing
    List<AssItem> rlist2 = new ArrayList<AssItem>() ;//all pass
    public List<AssItem> sortAss(List<AssItem> list){
        if (list.size()==0) return list;
        //按离当前日期最近的排序,逾期的逾期越久越往后
        List<AssItem> rlist = new ArrayList<AssItem>() ;//all
        if(list.get(0).getReTime()>=0){
            rlist1.add(list.get(0));
        }else {
            rlist2.add(list.get(0));
        }
        int count = list.size();
        for(int i=1;i<count;i++){
            if(list.get(i).getReTime()>=0){
                if (rlist1.size()==0) rlist1.add(list.get(i));
                else {
                for (int j=0;j<rlist1.size();j++){
                    if (list.get(i).getReTime()<=rlist1.get(j).getReTime()){
                        rlist1.add(j,list.get(i));
                        break;
                    }else if(j==rlist1.size()-1){
                        rlist1.add(list.get(i));
                        break;
                    }
                }
                }
            }else {
                if (rlist2.size()==0) rlist1.add(list.get(i));
                else {
                    for (int k=0;k<rlist2.size();k++){
                        if(list.get(i).getReTime()>=rlist2.get(k).getReTime()){
                            rlist2.add(k,list.get(i));
                            break;
                        }else if(k==rlist2.size()-1){
                            rlist2.add(list.get(i));
                            break;
                        }
                    }
                }
            }
        }
        rlist.addAll(rlist1);
        rlist.addAll(rlist2);
        return rlist;
    }

    public List<AssItem> getTimeLine(List<AssItem> list, int startH, int endH){
        List<AssItem> nextList = new ArrayList<AssItem>();
        String now = getNow();
        for (int i = 0; i < list.size();i++){
            if (startH<=list.get(i).getReTime()&&list.get(i).getReTime()<=endH){
                nextList.add(list.get(i));
            }
        }
        return nextList;
    }

    public String getNow(){
        Date date=new Date();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }


    public void addRow(Cursor cursor, int row_id) {

        TextView title = new TextView(getApplicationContext());
        TextView code = new TextView(getApplicationContext());
        TextView type = new TextView(getApplicationContext());
        TextView description = new TextView(getApplicationContext());
        TextView date = new TextView(getApplicationContext());
        TextView time = new TextView(getApplicationContext());
        TextView percentage = new TextView(getApplicationContext());


        TableRow row = new TableRow(getApplicationContext());
        params = new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.MATCH_PARENT, 1.0f);

        designTextView(title, cursor.getString(1));
        designTextView(code, cursor.getString(2));
        designTextView(type, cursor.getString(3));
        designTextView(description, cursor.getString(4));
        designTextView(date, cursor.getString(5));
        designTextView(time, cursor.getString(6));
        designTextView(percentage, cursor.getString(7));

        row.setId(row_id);
        row.addView(title);
        row.addView(code);
        row.addView(type);
        row.addView(description);
        row.addView(date);
        row.addView(time);
        row.addView(percentage);


        tableLayout.addView(row);
    }

    public void designTextView(TextView view, String data) {
        view.setText(data);
        view.setGravity(Gravity.START);
        view.setTextSize(15);
        view.setLayoutParams(params);
        view.setTypeface(ResourcesCompat.getFont(this, R.font.amiko));
        view.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.manager_menu, menu);
        return true;
    }

    @Override

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            return true;
        }else if (id == R.id.addalimit) {
            startActivity(new Intent(getApplicationContext(), Timecut1Activity.class));
        }
        else if(id == R.id.viewing) {
            startActivity(new Intent(getApplicationContext(), ViewingActivity.class));
        }

        else if (id == R.id.logout) {
            startActivity(new Intent(getApplicationContext(), LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
        }

        return super.onOptionsItemSelected(item);
    }


}